package edu.suda.xsap.controller;
//
//import com.codevip.tutorial.controller.common.Result;
//import com.codevip.tutorial.dto.UserDto;
//import com.codevip.tutorial.util.JwtUtil;
//import jakarta.servlet.http.HttpServletResponse;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//@RestController
//@Slf4j
//public class LoginController {
//
//    @Autowired
//    private AuthenticationManager authenticationManager;
//
//    //@PostMapping("/login")
//    @RequestMapping("/login")
//    public Result login(@RequestBody UserDto loginRequest, HttpServletResponse response) {
//
//        log.debug("username:{},password:{}", loginRequest.getUserName(), loginRequest.getUserPwd());
//        //
//        try {
//            // 这是一个Spring Security的接口，用于验证用户名和密码， 会调用UserDetailsService的loadUserByUsername方法
//            log.debug("==>开始调用authenticationManager的authenticate方法进行认证，参数是认证前的UsernamePasswordAuthenticationToken");
//            Authentication authentication = authenticationManager.authenticate(
//                    //传入一个未认证的Authentication对象, 不含权限
//                    new UsernamePasswordAuthenticationToken(loginRequest.getUserName(), loginRequest.getUserPwd())
//            );
//            //上面一旦正确返回，就是一个已经认证过的Authentication对象,含 权限信息
//            //
//            log.debug("==>认认成功，返回的认证对象是：{}", authentication);
//            //
//            log.debug("==>把认证好的对象，存放在SecurityContextHolder的上下文中");
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//            //
//            String token = JwtUtil.createToken(loginRequest.getUserName(), 3600);
//            log.debug("==> Token:{}", token);
//            //把token通过响应头传给客户端
//            response.setHeader(JwtUtil.getHeader(), token);
//            // 响应体
//            return Result.success();
//        } catch (AuthenticationException e) {
//            log.error(e.getMessage(), e);
//            Result result = Result.failure("用户名或密码错误", "");
//            result.setCode(HttpStatus.UNAUTHORIZED.value());
//            return result;
//        }
//    }
//}
